package org.xw.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.websocket.Session;

import java.util.Map;

public class JWTUtil {
    private static String REGISTER_CODE = "loadOfLoad";

    /**
     * 获取token令牌
     *
     * @param map
     * @return
     */
    public static String getToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        return builder.sign(Algorithm.HMAC256(REGISTER_CODE)).toString();
    }


    /**
     * 验证token
     *
     * @param token
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(REGISTER_CODE)).build().verify(token);
    }


    /**
     * 返回token，获取其中负载
     *
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token) {
        return JWT.require(Algorithm.HMAC256(REGISTER_CODE)).build().verify(token);
    }

    public static String analyzeToken(HttpServletRequest request, String headerName, String target) {
        String header = request.getHeader(headerName);
        if (header != null) {
            String[] strings = header.split(" ");
            DecodedJWT token = JWTUtil.getToken(strings[1]);
            Map<String, Claim> claims = token.getClaims();
            String s = claims.get(target).asString();
            return s;
        } else return null;
    }

    public static String sessionGetUserId(Session session) {
        // 获取用户账号(修改为获取token)
        String token = (String) session.getUserProperties().get("token");
        DecodedJWT token1 = JWTUtil.getToken(token);
        Map<String, Claim> claims = token1.getClaims();
        String userId = claims.get("user_id").asString();
        return userId;
    }
}
